#!/bin/bash
#Author: YangYi
#Date: 2025-05-10
#Version: v1


# ---------------------------初始化全局变量----------------------------

# 设置命名空间和资源名称
NAMESPACE="default"
DS_NAME="service-availability-detection-ds"
SERVICE_PORTS="80"

# 获取集群节点数量
NODE_COUNT=$(kubectl get nodes -o jsonpath='{.items[*].metadata.name}' | wc -w)

#米采集文件
PROMETHEUS_FILE="/home/patrol/prometheus_service_availability_detection.prom"

#普米指标格式化
TITLE="
# HELP prometheus_service_availability_detection_total Total number of WAL corruptions.\n# TYPE prometheus_service_availability_detection_total gauge
"


# ----------------------------功能模块函数-----------------------------

service_availability_detection(){

# 获取DaemonSet的所有Pod
PODS=$(kubectl get pods -n $NAMESPACE -o jsonpath='{.items[*].metadata.name}' | grep $DS_NAME)

if [ -z "$PODS" ]; then
    echo "未找到名为 $DS_NAME 的DaemonSet或其Pod"
    exit 1
fi
if ! command -v dos2unix &> /dev/null; then
    echo "错误:需要安装dos2unix命令行工具"
    exit 1
fi

echo -e $TITLE > $PROMETHEUS_FILE

# 同时检查所有Pod的端口
for POD in $PODS; do
    # 获取Pod的IP
    POD_IP=$(kubectl get pod $POD -n $NAMESPACE -o jsonpath='{.status.podIP}')

    # 获取curl的退出状态码和HTTP状态码
    response=$(curl -s --max-time 1 -w "%{http_code}" -o /dev/null http://$POD_IP:$SERVICE_PORTS/)
    #exit_code=$?
     
    #echo $POD_IP
    # 确保curl执行成功
    #if [ $exit_code -eq 0 ]; then 
        
      # 验证HTTP状态码是否为数字且等于200
      if [ "$response" -eq 200 ]; then
        #echo "探测接口$i: 成功"
        echo -e "prometheus_service_availability_detection_total{node=\""$POD_IP"\",status="正常"} "0 } >> $PROMETHEUS_FILE
      else
        #echo "探测接口$i: 失败"
        echo -e "prometheus_service_availability_detection_total{node=\""$POD_IP"\",status="异常"} "1 } >> $PROMETHEUS_FILE
      fi
    #else
      # 处理curl执行失败的情况（如网络不可达）
     # echo "异常 连接失败"
    #fi
done

dos2unix $PROMETHEUS_FILE > /dev/null 2>&1

}

service_availability_detection




